package com.itljm.cxrMarket.controller;

import com.itljm.cxrMarket.common.Result;
import com.itljm.cxrMarket.utils.BASE64DecodedMultipartFile;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ljm
 * @date 2024/12/11 14:58
 */
@RestController
@RequestMapping("/file")
@CrossOrigin
@Slf4j
public class FileUploadController {
    @Value("${upload.path}")
    private String uploadPath;
    @Value("${upload.imgPath}")
    private String imgPath;

    /**
     * 上传图片
     */
    @RequestMapping("uploadImg")
    public Result uploadFile(MultipartFile file) throws Exception {

        String fileName="";
        String originalFileName="";// 原始文件名
        String size="";
        try {
            fileName= file.getOriginalFilename();
            long fileS = file.getSize();

            originalFileName = fileName;
            String fileExtension = fileName.substring(fileName.lastIndexOf("."));// 文件后缀名
            if (file.isEmpty()) {
                return Result.fail("上传失败");
            } else {
                fileName = System.currentTimeMillis() + fileExtension;
                File dest = new File(uploadPath + imgPath + fileName);
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                file.transferTo(dest);

                DecimalFormat df = new DecimalFormat("#.00");
                if (fileS < 1024) {
                    size = df.format((double) fileS) + "B";
                } else if (fileS < 1048576) {
                    size = df.format((double) fileS / 1024) + "KB";
                } else if (fileS < 1073741824) {
                    size = df.format((double) fileS / 1048576) + "MB";
                } else {
                    size = df.format((double) fileS / 1073741824) +"GB";
                }
            }

        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.fail("上传失败");
        }

        Map<String, Object> map = new HashMap();
        map.put("url", fileName);//图片url
        map.put("fileName", fileName);//图片名称
        map.put("originalFileName", originalFileName);
        map.put("fileSize", size);

        return Result.ok(map);

    }

    /**
     * 上传头像
     */
    @RequestMapping("uploadAvatar")
    public Result uploadAvatar(MultipartFile file) throws Exception {

        String fileName="";
        String originalFileName="";// 原始文件名
        String size="";
        try {
            fileName= file.getOriginalFilename();
            long fileS = file.getSize();
            originalFileName = fileName;

            String fileExtension = fileName.substring(fileName.lastIndexOf("."));// 文件后缀名
            if (file.isEmpty()) {
                return Result.fail("上传失败");
            } else {
                fileName = System.currentTimeMillis() + fileExtension;
                File dest = new File(uploadPath + imgPath + fileName);
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                file.transferTo(dest);

                DecimalFormat df = new DecimalFormat("#.00");
                if (fileS < 1024) {
                    size = df.format((double) fileS) + "B";
                } else if (fileS < 1048576) {
                    size = df.format((double) fileS / 1024) + "KB";
                } else if (fileS < 1073741824) {
                    size = df.format((double) fileS / 1048576) + "MB";
                } else {
                    size = df.format((double) fileS / 1073741824) +"GB";
                }
            }

        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.fail("上传失败");
        }

        Map<String, Object> map = new HashMap();
        map.put("url", fileName);//图片url
        map.put("fileName", fileName);//图片名称
        map.put("originalFileName", originalFileName);
        map.put("fileSize", size);

        return Result.ok(map);

    }

    /**
     * 文件下载
     */
    @RequestMapping(path = "filedownload")
    public void fileDownload(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String fileName) {

        String filePath = uploadPath +"files" + File.separator;

        File file = new File(filePath+fileName);
        if (!file.exists()) {
            log.info("文件不存在");
        }
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
             ServletOutputStream sos = httpServletResponse.getOutputStream();) {
            //二进制文件流形式
            httpServletResponse.setContentType("application/octet-stream");
            //设置文件的下载方式
            httpServletResponse.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
            byte[] buffer = new byte[1 << 10];
            int readLen = 0;
            while ((readLen = bis.read(buffer, 0, buffer.length)) > 0) {
                sos.write(buffer, 0, readLen);
            }
            log.info("下载成功");
        } catch (Exception e) {
            log.error("下载失败!"+e.getMessage());
        }

    }

    @RequestMapping("h5UploadImg")
    @ResponseBody
    public Object h5UploadImg(HttpServletRequest request,String base64){
        Map map = new HashMap();
        try {
            MultipartFile file = BASE64DecodedMultipartFile.base64ToMultipart(base64);

            String path= null;
            String fileName="";
            String originalFileName="";
            String size="";
            try {
                path = uploadPath + "images" + File.separator;

                fileName= file.getOriginalFilename();

                long fileS = file.getSize();

                originalFileName=fileName;
                String fileExtension=fileName.substring(fileName.lastIndexOf("."));
                if (file.isEmpty()) {
                    return Result.fail("操作失败");
                } else {
                    fileName=System.currentTimeMillis()+fileExtension;
                    File dest = new File(path+fileName);
                    if (!dest.getParentFile().exists()) { // 判断文件父目录是否存在
                        dest.getParentFile().mkdir();
                    }
                    file.transferTo(dest);

                    DecimalFormat df = new DecimalFormat("#.00");
                    if (fileS < 1024) {
                        size = df.format((double) fileS) + "B";
                    } else if (fileS < 1048576) {
                        size = df.format((double) fileS / 1024) + "KB";
                    } else if (fileS < 1073741824) {
                        size = df.format((double) fileS / 1048576) + "MB";
                    } else {
                        size = df.format((double) fileS / 1073741824) +"GB";
                    }
                }
            } catch (Exception e) {
                log.error(e.getMessage());
                return Result.fail("操作失败");
            }

            Map<String, Object> mapData = new HashMap();
            mapData.put("src", "/res/uploadFile/" + fileName);//图片url
            mapData.put("fileName", fileName);//图片名称，这个会显示在输入框里
            mapData.put("originalFileName", originalFileName);
            mapData.put("fileSize", size);
            map.put("code", 0);//0表示成功，1失败
            map.put("msg", "上传成功");//提示消息
            map.put("data", mapData);//提示消息

            map.put("status",0);
        }catch (Exception e){
            map.put("status",-1);
            map.put("msg",e.getMessage());
        }
        return map;
    }

    /**
     * 视频文件上传
     */
    @ResponseBody
    @RequestMapping(value = "/videoFile", method = {RequestMethod.POST})
    public Object headImg(@RequestParam(value="file",required=false) MultipartFile attach, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map map = new HashMap();

        try {
            String path = null;
            String fileName = "";
            String originalFileName = "";
            String size = "";
            //判断文件是否为空
            if(attach.isEmpty()){
                return Result.fail("操作失败");
            }else {
                try {
                    path = uploadPath +"video" +File.separator;
                    String oldFileName = attach.getOriginalFilename();//原文件名
                    long fileS = attach.getSize();
                    originalFileName = oldFileName;
                    String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
                    fileName = System.currentTimeMillis()+"."+prefix;
                    File targetFile = new File(path, fileName);  //创建文件
                    if(!targetFile.exists()){  //判断文件夹是否存在
                        targetFile.mkdirs();
                    }
                    attach.transferTo(targetFile);

                    DecimalFormat df = new DecimalFormat("#.00");
                    if (fileS < 1024) {
                        size = df.format((double) fileS) + "B";
                    } else if (fileS < 1048576) {
                        size = df.format((double) fileS / 1024) + "KB";
                    } else if (fileS < 1073741824) {
                        size = df.format((double) fileS / 1048576) + "MB";
                    } else {
                        size = df.format((double) fileS / 1073741824) +"GB";
                    }
                } catch (Exception e) {
                    log.error(e.getMessage());
                    return Result.fail("操作失败");
                }
            }

            HashMap<String,Object> mapData=new HashMap();
            mapData.put("src", "/res/uploadFile/" + fileName);
            mapData.put("fileName", fileName);
            mapData.put("originalFileName", originalFileName);
            mapData.put("fileSize", size);
            map.put("code",0);
            map.put("msg","上传成功");
            map.put("data",mapData);

            map.put("status",0);
        }catch (Exception e){
            map.put("status",-1);
            map.put("msg",e.getMessage());
        }
        return map;
    }

    /**
     * 图片浏览
     * @param imageName
     * @return
     */
    @GetMapping(value = "/image", produces = MediaType.IMAGE_JPEG_VALUE) // 注意注解的参数，produces = MediaType.IMAGE_JPEG_VALUE
    public byte[] getImage(String imageName) throws IOException {
        // 图片文件路径
        String imagePath = uploadPath + imgPath + imageName;

        // 读取图片文件并返回字节数组
        File file = new File(imagePath);
        return Files.readAllBytes(file.toPath());
    }
}
